package v1

import (
	"github.com/dgrijalva/jwt-go"
	"pq/controllers"
	"strings"
)
type Playload struct {
	Exp int64
	Iss string
}
var ignores = []string{
	"/v1/point_categories",
	"/v1/test_categories/code",
	"/v1/test_categories/area",
	"/v1/user/info-of-phone",
	"/v1/user/area-by-phone",
}
type TokenCheckController struct{
	Username string
	Uid string
	controllers.BaseController
}
func (tcc *TokenCheckController)Prepare(){
	for _,ignore := range ignores{
		if strings.Index(tcc.Ctx.Request.URL.String(),ignore) == 0 {
			return
		}
	}
	//Lo que quieras hacer en todos los controladores
	//tokenString := tcc.Ctx.Input.Query("access_token")
	headAuth := tcc.Ctx.Input.Header("Authorization")
	tokenString := strings.Replace(headAuth,"Bearer ","",1)
	//beego.Debug("token:"+tokenString)
	if tokenString =="" {
		tcc.Fail("Please specify token","")
		return
	}
	tk, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte("e9e81816872ed889f4de9a04661ea98a"), nil
	})
	if err != nil  {
		tcc.Fail("Token error:"+err.Error(),"")
		return
	}
	if claims, ok := tk.Claims.(jwt.MapClaims); ok &&  tk.Valid {
		params := strings.Split(claims["user_name"].(string),"_")
		if len(params) >= 2{
			tcc.Uid = params[0]
			tcc.Username = params[1]
			//log.Success("%s,%s",tcc.Uid,tcc.Username)
		}else{
			tcc.Fail("Token error : wrong claims","")
		}
	} else{
		tcc.Fail("Token error : invalid token","")
	}
	return
}
func (tcc *TokenCheckController) Option(){
	tcc.Fail("Options invoke","")
}